package com.fuatnow.game.connection;

import com.fuatnow.game.handler.GateMineSweepConnectionHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * Created by fuatnow on 17/2/10.
 */
public class GateMineSweepConnection
{
    private static final Logger logger = LoggerFactory.getLogger(GateMineSweepConnection.class);

    public static void startGateMineSweepConnection(String ip , int port)
    {
        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel)
                            throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        // 字符串解码 和 编码
                        ByteBuf[] by = new ByteBuf[]{ Unpooled.wrappedBuffer(new byte[]{0})};
//                        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter()));
                        pipeline.addLast("frameEncoder",new LengthFieldPrepender(4));
                        pipeline.addLast("encoder", new StringEncoder(Charset.forName("UTF-8")));
                        pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(1048576,0,4,0,4));
                        pipeline.addLast("decoder", new StringDecoder(Charset.forName("UTF-8")));
                        pipeline.addLast("GateMineSweepConnection", new GateMineSweepConnectionHandler());
                    }
                });

        bootstrap.connect(ip, port);
    }

}
